package com.dff.jrfw;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.dff.jrfw.databinding.ActivityInputCodeBinding;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtilsTwo;
import com.dff.jrfw.utils.CountDownHelper;
import com.dff.jrfw.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class InputCodeActivity extends BaseActivity implements View.OnClickListener {

    private ActivityInputCodeBinding binding;
    private String username;
    private String mobile;
    private String typeFrom;


    public static void callMe(Activity context, String username, String mobile, String typeFrom) {
        Intent intent = new Intent(context, InputCodeActivity.class);
        intent.putExtra("username", username);
        intent.putExtra("mobile", mobile);
        intent.putExtra("typeFrom", typeFrom);
        if (typeFrom.equals("login")) {
            context.startActivityForResult(intent, 666);
        } else {
            context.startActivity(intent);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_input_code);
        username = getIntent().getStringExtra("username");
        mobile = getIntent().getStringExtra("mobile");
        typeFrom = getIntent().getStringExtra("typeFrom");
        initView();
        sendCertSmsCode();
    }

    private void initView() {
        binding.tvMobile.setText(mobile.substring(0, 3) + "****" + mobile.substring(7));
        binding.ivBack.setOnClickListener(this);
        binding.btnNext.setOnClickListener(this);
        binding.tvSendCode.setOnClickListener(this);
        binding.ivInputClearCode.setOnClickListener(this);
        binding.etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etPayPsd = charSequence.toString().trim();
                if (etPayPsd.length() == 0) {
                    binding.ivInputClearCode.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClearCode.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        CountDownHelper countDownHelper = new CountDownHelper(binding.tvSendCode, "重新发送", 60, 1);
        countDownHelper.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_send_code:
                sendCertSmsCode();
                break;
            case R.id.btn_next:
                String etCode = binding.etCode.getText().toString().trim();
                if (TextUtils.isEmpty(etCode)) {
                    ToastUtil.toast("请输入验证码");
                    return;
                }
                verifyCertSmsCode(etCode);
                break;
            case R.id.iv_input_clear_code:
                binding.etCode.setText("");
                break;
        }
    }


    private void sendCertSmsCode() {
        showLoading();
        RetrofitUtilsTwo.getService().sendCertSmsCode("1", "1", mobile).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            ToastUtil.toast("验证码已发送");
                            CountDownHelper countDownHelper = new CountDownHelper(binding.tvSendCode, "重新发送", 60, 1);
                            countDownHelper.start();
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void verifyCertSmsCode(String checkCode) {
        showLoading();
        RetrofitUtilsTwo.getService().verifyCertSmsCode("1", "1", mobile, checkCode).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            SetPayPsdActivity.callMe(InputCodeActivity.this, username, mobile, checkCode, typeFrom);
                        } else if (code == 906) {
                            ToastUtil.toast("验证码错误");
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 666 && resultCode == 888) {
            setResult(888);
            finish();
        }
    }


}